package com.csdj.music.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.music.utils.JwtTokenUtil;
import com.csdj.music.vo.Admin;
import com.csdj.music.service.AdminService;
import com.csdj.music.mapper.AdminMapper;
import com.csdj.music.vo.RespBean;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
* @author ZouLi
* @description 针对表【admin】的数据库操作Service实现
* @createDate 2023-03-13 15:36:40
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{
    /**
     AdminMapper
     **/
    @Autowired(required = false)
    private AdminMapper adminMapper;

    /**
     * 注入userDetailsService
     **/
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 注入passwordEncoder 密码加密
     **/
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 注入JwtUtil token工具类
     **/
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 请求头信息
     **/
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public Admin getAdminByAdminName(String adminName) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("name",adminName));
    }

    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String sessionCode = (String)request.getSession().getAttribute("backCode");
        if (StringUtils.isBlank(code) || !StringUtils.equals(sessionCode,code)){
            return RespBean.error("验证码错误！");
        }

        // 根据用户名加载用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())){
            return RespBean.error("用户名或密码错误！");
        }

        // 判断账号是否启用
        if (!userDetails.isEnabled()){
            return RespBean.error("账号已被禁用，请联系管理员！");
        }

        // 用户授权
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // 将用户授权信息存储到security上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        // 存储token信息
        Map<String,Object> tokenMap = new HashMap<String,Object>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return RespBean.success("登录成功！",tokenMap);
    }
}




